<template>
  <div @keyup.enter="getData()">
    <input type="text" style="display: none" />
    <el-form class="query-form" :inline="true" :model="params">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="params.agency_type"
          placeholder="机构类型查询"
          @change="getData()"
          clearable
        >
          <el-option
            v-for="(label, value) of enumOrgType"
            :label="label"
            :value="value"
            :key="value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.agency_name"
          @change="getData()"
          clearable
          placeholder="机构名称查询"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getData()" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item v-if="showButton">
        <el-button type="primary" @click="edit()" icon="el-icon-plus">新增</el-button>
      </el-form-item>
      <el-form-item v-if="showButton">
        <el-button type="primary" @click="dialogImportVisible = true">
          <i class="fa fa-fw fa-upload"></i>
          导入
        </el-button>
      </el-form-item>
    </el-form>
    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            {{ enumOrgType[scope.row.agency_type] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="机构名称" prop="agency_name"></el-table-column>
        <el-table-column align="center" label="账号名称" prop="user_name"></el-table-column>
        <el-table-column align="center" label="地址" prop="address"></el-table-column>
        <el-table-column align="center" label="联系人" prop="contact"></el-table-column>
        <el-table-column align="center" label="联系电话" prop="mobile_no"></el-table-column>
        <el-table-column align="center" label="授信金额(万元)">
          <template slot-scope="scope">
            {{ scope.row.credit_amount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="保证金/资本金/资金池(万元)">
          <template slot-scope="scope">
            {{ scope.row.margin_amount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="合作产品" prop="load_products"></el-table-column>
        <!-- <el-table-column align="center"
                         label="合作模式"
                         prop="coo_model"></el-table-column> -->
        <el-table-column align="center" label="操作" v-if="showButton">
          <template slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="editrow(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteData(scope.row)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>
    <div class="query-pagination">
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <el-dialog
      :title="`${formData.credit_agency_info_id ? '编辑' : '添加'}合作机构`"
      width="60%"
      top="30px"
      :close-on-click-modal="false"
      :before-close="handleClose"
      :visible.sync="editVisible"
    >
      <el-form :model="formData" :rules="rules" ref="form" label-width="150px" v-loading="loading">
        <el-form-item label="类型" prop="agency_type">
          <el-select
            v-model="formData.agency_type"
            :disabled="!!formData.credit_agency_info_id"
            class="form-control-ml"
          >
            <el-option
              :key="key"
              :label="value"
              :value="key"
              v-for="(value, key) in enumOrgType"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构名称" prop="agency_name">
          <!-- <select-customer-bank v-model="formData.agency_name"
                                :disabled="formData.credit_agency_info_id && +formData.agency_type === 1"
                                class="form-control-ml"
                                :orgClass="formData.agency_type"
                                @change="setId"></select-customer-bank> -->
          <el-input
            v-model="formData.agency_name"
            placeholder="请输入机构名称"
            @change="nameChange"
            class="form-control-ml"
          ></el-input>
        </el-form-item>
        <el-form-item label="账号名称" prop="user_name">
          <el-input
            v-model="formData.user_name"
            class="form-control-ml"
            placeholder="账号由数字字母以及下划线组成"
            @input="userNameCheck"
            @change="userChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="行政级别" prop="org_region_lever">
          <c-select
            :options="enumOrganLevel"
            class="form-control-ml"
            placeholder="请选择行政级别"
            v-model="formData.org_region_lever"
          ></c-select>
        </el-form-item>
        <el-form-item label="地址" prop="address_code">
          <select-address
            v-model="formData.address_code"
            class="form-control-ml"
            :auto-top="true"
          ></select-address>
        </el-form-item>
        <el-form-item label="地址详情" prop="address_detail">
          <el-input v-model="formData.address_detail" class="form-control-ml"></el-input>
        </el-form-item>
        <el-form-item label="上级机构" v-if="formData.agency_type === '1'">
          <select-agency-info
            v-model="formData.parent_code"
            class="form-control-ml"
            :disabled="formData.credit_agency_info_id && +formData.agency_type === 1"
          ></select-agency-info>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formData.contact" class="form-control-ml"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile_no">
          <el-input v-model="formData.mobile_no" class="form-control-ml"></el-input>
        </el-form-item>
        <el-form-item label="授信金额">
          <el-input
            v-model="formData.credit_amount"
            type="number"
            class="form-control-ml"
            placeholder="请输入授信金额"
          >
            <span slot="append">万元</span>
          </el-input>
        </el-form-item>
        <el-form-item label="保证金/资本金/资金池">
          <el-input
            v-model="formData.margin_amount"
            type="number"
            class="form-control-ml"
            placeholder="请输入保证金/资本金/资金池"
          >
            <span slot="append">万元</span>
          </el-input>
        </el-form-item>
        <el-form-item label="合作产品">
          <select-product
            v-model="product"
            class="form-control-ml"
            multiple
            @change="productString"
          ></select-product>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.coo_model"
            class="form-control-ml"
            type="textarea"
            autosize
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="submit" :loading="loading" class="btn-long" type="primary">
            保存
          </el-button>
          <el-button @click="handleClose" class="btn-long">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <import-excel
      excel-template="/static/files/机构导入模板.xlsx"
      title="导入机构"
      :post-api="postUrl"
      :visible.sync="dialogImportVisible"
      @success="getData(params.index)"
    ></import-excel>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumOrgType, enumOrganLevel } from '@/credit/plugins/enum'
import SelectAddress from '@/components/select/SelectAddress'
import SelectProduct from '@/credit/components/select/SelectCreditGoodsName'
import SelectAgencyInfo from '@/credit/components/select/SelectAgencyInfo'
// import { createOrgCorp } from '@/common/api/auth'
import { phoneValidator } from '@/common/plugins/validator'
import { queryTrouble } from '@vimi/utils-api'
import ImportExcel from '@/components/ImportExcel'
// const enumOrg = {
//   1: 'org_bank',
//   2: 'org_agr_leader',
//   3: 'org_gov_ny',
//   4: 'org_social',
//   5: 'org_supply_market'
// }

export default {
  components: {
    ImportExcel,
    SelectAgencyInfo,
    SelectProduct,
    SelectAddress,
  },
  props: {},
  data() {
    const nameValidator = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入机构名称'))
      } else if (!this.agencyName) {
        callback(new Error('机构名称已存在!'))
      } else {
        callback()
      }
    }
    const userValidator = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录账号'))
      } else if (!this.userName) {
        callback(new Error('名称已存在!'))
      } else {
        callback()
      }
    }
    return {
      agencyName: true,
      userName: true,
      tableData: [],
      params: {
        index: 1,
        size: 10,
      },
      totalCount: 0,
      editVisible: false,
      dialogImportVisible: false,
      tableName: 'credit_agency_info',
      formData: {},
      tableId: '',
      rules: {
        agency_type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        address_code: [{ required: true, message: '请选择地址', trigger: 'change' }],
        mobile_no: [
          {
            required: true,
            validator: phoneValidator,
            message: '手机号或座机号（如;0856-1234567）',
            trigger: 'blur',
          },
        ],
        contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        agency_name: [{ required: true, validator: nameValidator, trigger: 'blur' }],
        user_name: [{ required: true, validator: userValidator, trigger: 'blur' }],
      },
      product: [],
      loading: false,

      postUrl: '',
    }
  },
  computed: {
    ...mapGetters(['job', 'clientId', 'user']),
    showButton() {
      return ['org_credit_super', 'org_c_manage', 'org_corp'].includes(this.job)
    },
    isUserTown() {
      return this.user.orgRegionLever === 3
    },
    level() {
      return this.user.orgRegionLever
    },
    enumOrgType() {
      if (this.isUserTown) {
        return {
          1: '银行',
          3: '政府',
        }
      }
      return enumOrgType
    },
    enumOrganLevel() {
      const enumOrg = {}
      Object.keys(enumOrganLevel).forEach(item => {
        if (item >= this.level) {
          enumOrg[item] = enumOrganLevel[item]
        }
      })
      return enumOrg
    },
  },
  watch: {},
  created() {
    this.params.address_code = this.$utils.getAddressCode()
    this.postUrl =
      '/api/credit/import/' +
      queryTrouble('credit_agency_info', {
        importKey: 'credit_agency_info_template',
        'service_id.eq': this.clientId,
      })
    this.getData()
  },
  mounted() {},
  methods: {
    userNameCheck(val) {
      const realName = val.replace(/[^A-Za-z0-9-_]+$/g, '')
      this.$set(this.formData, 'user_name', realName)
    },
    nameChange(val) {
      if (!val) {
        return
      }
      this.$api.getData('credit', this.tableName, { 'agency_name.eq': val }).then(res => {
        const data = (res && res.data && res.data[0]) || {}

        if (data.agency_id && this.formData.agency_id !== data.agency_id) {
          this.agencyName = false
        } else {
          this.agencyName = true
        }
        this.$refs.form.validateField('agency_name')
      })
    },
    userChange(val) {
      if (!val) {
        return
      }
      this.$api.getData('credit', this.tableName, { 'user_name.eq': val }).then(res => {
        const data = (res && res.data && res.data[0]) || {}

        if (data.agency_id && this.formData.agency_id !== data.agency_id) {
          this.userName = false
        } else {
          this.userName = true
        }
        this.$refs.form.validateField('user_name')
      })
    },
    handleClose() {
      this.product = []
      this.editVisible = false
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.toSave()
        } else {
          this.$message.warning('输入错误，请检查后重试！')
          return false
        }
      })
    },
    async toSave() {
      if (this.formData.credit_agency_info_id) {
        this.putData()
      } else {
        this.postData()
      }
    },
    async putData() {
      const { address, ...data } = this.formData
      const [res, err] = await this.$utils.promise(
        this.$api.updateData('credit', this.tableName, this.formData.credit_agency_info_id, data)
      )
      this.loading = false
      if (res) {
        this.$message.success('保存成功！')
        this.getData()
        this.handleClose()
      } else {
        this.$message.error(`保存失败，请重试！（${err.status}）`)
      }
    },
    async postData() {
      this.formData.agency_code = ''
      this.formData.service_id = this.$store.getters.org.clientId
      const [res, err] = await this.$utils.promise(
        this.$api.addData('credit', this.tableName, this.formData)
      )
      this.loading = false
      if (res) {
        this.$message.success('保存成功！')
        this.getData()
        this.handleClose()
      } else {
        this.$message.error(`保存失败，请重试！（${err.status}）`)
      }
    },
    productString() {
      this.formData.load_products = this.product.join(',')
    },
    getData(index = 1) {
      this.params.index = index
      this.$api
        .getData('credit', 'credit_agency_info_view', this.params, {
          create_time: 'desc',
        })
        .then(res => {
          this.tableData = res.data.data
          this.totalCount = res.data.totalCount
        })
    },
    edit() {
      this.formData = {}
      this.editVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    editrow(p) {
      this.formData = { ...p }
      if (this.formData.load_products) {
        this.product = this.formData.load_products.split(',')
      }
      this.userName = true
      this.agencyName = true
      this.editVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.credit_agency_info_id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
  },
}
</script>
<style scoped></style>
